<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Wallet extends Model
{
    protected $table = 'wallet';
    public $timestamps = false;

    // 扣除usdt余额
    public function reduceUsdt($user_id, $money, $coin_id = 1, $type = 1,$operation_type ='buy_node')
    {
        $wallet = self::where('user_id', $user_id)->where('coin_id', $coin_id)->where('type', $type)->first();
        if (!$wallet) {
            return false;
        }
        $before_balance = $wallet->balance;
        $change_balance = $money;
        $after_balance = $before_balance - $change_balance;

        if ($before_balance < $change_balance) {
            return false;
        }


        $wallet->balance = $after_balance;
        $ret = $wallet->save();

        if($ret){
            $detail = new WalletBalanceDetail();
            $detail->user_id = $user_id;
            $detail->coin_id = $coin_id;
            $detail->before_balance = $before_balance;
            $detail->change_balance = $change_balance;
            $detail->after_balance = $after_balance;
            $detail->type = 'sub';
            $detail->operation_type = $operation_type;
            $detail->create_time = date('Y-m-d H:i:s', time());
            $detail->balance_type = $type;
            $detail->user_id_send = $user_id;
            $detail->source_id = 0;
            return $detail->save();
        }
        return false;
    }
    // 扣除usdt余额
    public function incrementUsdt($user_id, $money, $coin_id = 1, $type = 1,$operation_type ='buy_node')
    {
        $wallet = self::where('user_id', $user_id)->where('coin_id', $coin_id)->where('type', $type)->first();
        if (!$wallet) {
            return false;
        }
        $before_balance = $wallet->balance;
        $change_balance = $money;
        $after_balance = $before_balance + $change_balance;

        $wallet->balance = $after_balance;
        $ret = $wallet->save();

        if($ret){
            $detail = new WalletBalanceDetail();
            $detail->user_id = $user_id;
            $detail->coin_id = $coin_id;
            $detail->before_balance = $before_balance;
            $detail->change_balance = $change_balance;
            $detail->after_balance = $after_balance;
            $detail->type = 'add';
            $detail->operation_type = $operation_type;
            $detail->create_time = date('Y-m-d H:i:s', time());
            $detail->balance_type = $type;
            $detail->user_id_send = $user_id;
            $detail->source_id = 0;
            return $detail->save();
        }
        return false;
    }
}
